from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

class ProductListPage:
    def __init__(self, driver):
        self.driver = driver
        # 页面元素定位器
        self.product_list_locator = (By.ID, "product-list")
        self.search_box_locator = (By.ID, "search-box")
        self.sort_by_locator = (By.ID, "sort-by")
        self.filter_options_locator = (By.ID, "filter-options")
        self.product_item_locator = (By.CLASS_NAME, "product-item")
        self.product_name_locator = (By.CLASS_NAME, "product-name")
        self.product_price_locator = (By.CLASS_NAME, "product-price")
        self.next_page_button_locator = (By.ID, "next-page-button")
        self.previous_page_button_locator = (By.ID, "previous-page-button")
        self.page_number_locator = (By.ID, "page-number")

    def navigate(self):
        self.driver.get('http://example.com/products')

    def search_product(self, query):
        search_box = WebDriverWait(self.driver, 10).until(
            EC.presence_of_element_located(self.search_box_locator)
        )
        search_box.send_keys(query)
        search_box.submit()

    def sort_products(self, option):
        sort_by = WebDriverWait(self.driver, 10).until(
            EC.presence_of_element_located(self.sort_by_locator)
        )
        sort_by.send_keys(option)

    def filter_products(self, option):
        filter_options = WebDriverWait(self.driver, 10).until(
            EC.presence_of_element_located(self.filter_options_locator)
        )
        filter_options.send_keys(option)

    def get_product_list(self):
        product_list = WebDriverWait(self.driver, 10).until(
            EC.presence_of_all_elements_located(self.product_item_locator)
        )
        return product_list

    def get_product_name(self, index=0):
        product_name = WebDriverWait(self.driver, 10).until(
            EC.presence_of_all_elements_located(self.product_name_locator)
        )[index]
        return product_name.text

    def get_product_price(self, index=0):
        product_price = WebDriverWait(self.driver, 10).until(
            EC.presence_of_all_elements_located(self.product_price_locator)
        )[index]
        return product_price.text

    def click_next_page(self):
        next_page_button = WebDriverWait(self.driver, 10).until(
            EC.element_to_be_clickable(self.next_page_button_locator)
        )
        next_page_button.click()

    def click_previous_page(self):
        previous_page_button = WebDriverWait(self.driver, 10).until(
            EC.element_to_be_clickable(self.previous_page_button_locator)
        )
        previous_page_button.click()

    def get_current_page_number(self):
        page_number = WebDriverWait(self.driver, 10).until(
            EC.visibility_of_element_located(self.page_number_locator)
        )
        return int(page_number.text)